package com.hello.service.impl;

import com.hello.service.ExecutorSchedulerService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;

/**
 * @author : bamboo brother
 * @date : 2017-04-12
 */
@Service
public class ExecutorSchedulerServiceImpl implements ExecutorSchedulerService {

    Log log = LogFactory.getLog(ExecutorSchedulerServiceImpl.class);

    @Resource
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    //Map<String, Thread> map = new HashMap<>();

    Map<String, Future> map = new HashMap<>();

    public void addExecutorScheduler (String taskId) {
        /**
         * 使用线程池实现
         */
        Future future = threadPoolTaskExecutor.submit(new AddTask(taskId));

        map.put(taskId, future);

        /**
         * 使用纯线程实现
         */
        //AddTask2 addTask2 = new AddTask2(taskId);
        //
        //addTask2.start();
        //
        //map.put(taskId, addTask2);
    }

    public void pauseTask (String taskId) {
        /**
         * 线程池实现
         */
        Future future = map.get(taskId);

        if (future != null) {
            future.cancel(true);
        }

        /**
         * 纯线程实现
         */
        //Thread thread = map.get(taskId);
        //
        //if ( thread != null) {
        //    thread.interrupt();
        //}
    }

    class AddTask implements Runnable{

        private String taskId;

        public AddTask(String taskId) {
            this.taskId = taskId;
        }

        @Override
        public void run() {
            Future future = map.get(taskId);

            for (int i = 0;i < 100000000; i ++) {
                if (future!= null && future.isCancelled()) {
                    break;
                }

                log.info("i is : " + i);
            }
        }
    }

    class AddTask2 extends Thread {
        private String name;

        public AddTask2(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            for (int i = 0;i < 100000000; i ++) {
                if (Thread.currentThread().isInterrupted()) {
                    break;
                }
                System.out.println(i);
            }
        }
    }

}
